<template>
  <div v-loading="loading" class="types" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addCommodityTypeDialogVisible = true">添加分类</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)"> 批量启用 </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)"> 批量禁用 </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)"> 批量删除 </el-dropdown-item>
              <el-dropdown-item @click="onVisibleTypeMultipleUpdate"
                >批量修改可见类型</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        row-key="id"
        :tree-props="{ children: 'childData' }"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
          fixed="left"
          :align="'center'"
        />

        <!-- 类型名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="分类名称" min-width="200" />

        <el-table-column label="可见类型" width="100">
          <template #default="{ row }">
            <template v-if="row.visibilityType === 1">全部可见</template>
            <template v-else-if="row.visibilityType === 2">网点可见</template>
            <template v-else-if="row.visibilityType === 3">公司可见</template>
            <template v-else>小程序不可见</template>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <HStatus v-if="!scope.row.status">启用</HStatus>
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
          </template>
        </el-table-column>

        <!--操作-->
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer" style="display: flex; justify-content: flex-end">
              <h-link v-if="scope.row.level != 3" @click="addDataChildren(scope.row)"
                >添加子类</h-link
              >
              <h-link @click="editData(scope.row)">编辑</h-link>
              <h-link type="error" @click="onListDelBtnClick(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑  类型弹窗 -->
    <h-dialog v-model="addDialog" :title="dialogTitle" :loading="dialogLoading">
      <el-form
        ref="formRef"
        label-position="top"
        :rules="rules"
        :model="form"
        class="modal_form_content"
        inline-message
      >
        <el-form-item v-if="dialogTitle == '添加下级'" label="上级分类">
          <el-input v-model.trim="objItem.parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称" class="form-item" prop="name">
          <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分类状态" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false">启用</el-radio>
            <el-radio :value="true">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false"> 取消 </HButton>
      </template>
    </h-dialog>

    <AddCommodityType
      v-model:visible="addCommodityTypeDialogVisible"
      type="commodity"
      @update="getList"
    />

    <UpdateCommodityType
      v-model:visible="updateCommodityTypeDialogVisible"
      :update-type="currentEditType"
      type="commodity"
      @update="getList"
    />

    <AddChildCommodityType
      v-model:visible="addChildCommodityTypeDialogVisible"
      :parent-type="currentAddChildCommodityType"
      type="commodity"
      @update="getList"
    />

    <good-type-visible-type-multiple-update-modal
      v-model:visible="multipleUpdateVisibleTypeModalVisible"
      :id-list="multipleUpdateVisibleTypeGoodTypeIdList"
      @update="getList"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, h } from 'vue'
  import { ElMessage, ElMessageBox, ElDivider } from 'element-plus'
  import type { FormInstance, TableInstance } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import { typeList, typeSave, typeDisable, typeDelete } from '@/api/goodsSet'
  import { CommodityType } from './types'
  import AddCommodityType from '@/components/pages/common/type/add-type/AddType.vue'
  import UpdateCommodityType from '@/components/pages/common/type/update-type/UpdateType.vue'
  import AddChildCommodityType from '@/components/pages/common/type/add-child-type/AddChildType.vue'
  import { UpdateCommodityTypeProps } from '@/components/pages/common/type/update-type/types'
  import GoodTypeVisibleTypeMultipleUpdateModal from '@/components/pages/good/TypeVisibleTypeMultipleUpdateModal.vue'

  // 添加子类弹窗显示状态
  const addChildCommodityTypeDialogVisible = ref(false)

  // 编辑分类弹窗显示状态
  const updateCommodityTypeDialogVisible = ref(false)

  // 添加分类弹窗显示状态
  const addCommodityTypeDialogVisible = ref(false)

  // 当前正在编辑的分类
  const currentEditType = ref<UpdateCommodityTypeProps>({
    name: '',
    id: '',
    parentId: '',
    status: false,
    level: 1,
    visibilityType: 1,
  })

  // 当前正在添加子类的分类
  const currentAddChildCommodityType = ref({
    name: '',
    parentId: '',
    status: false,
    level: 1,
    id: '',
  })

  // 批量更新可见类型弹窗显示状态
  const multipleUpdateVisibleTypeModalVisible = ref(false)

  // 需要更新可见的产品id集合
  const multipleUpdateVisibleTypeGoodTypeIdList = ref<Array<string>>([])

  /**
   * 批量更新可见类型
   */
  const onVisibleTypeMultipleUpdate = () => {
    multipleUpdateVisibleTypeGoodTypeIdList.value = selecttion.value
    // const firstLevelTypeIdList = tableData.value.map((item) => item.id)
    // selecttion.value.forEach((id) => {
    //   if (firstLevelTypeIdList.includes(id)) {
    //     multipleUpdateVisibleTypeGoodTypeIdList.value.push(id)
    //   }
    // })
    multipleUpdateVisibleTypeModalVisible.value = true
  }

  /**
   * 编辑类型
   * @param {Object} commodityType - 分类
   */
  const editData = (commodityType: CommodityType) => {
    currentEditType.value = {
      id: commodityType.id,
      parentId: commodityType.parentId,
      name: commodityType.name,
      status: commodityType.status,
      level: commodityType.level,
    }
    currentEditType.value.visibilityType = commodityType.visibilityType
    updateCommodityTypeDialogVisible.value = true
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  /**
   * 删除分类
   * @param {Object} commodityType - 分类
   */
  const onListDelBtnClick = (commodityType: CommodityType) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(commodityType, true)
      form.id = commodityType.id
      changeStatus(4)
    }
  }

  /**
   * 添加下级
   * @param {Object} commodityType - 分类
   */
  const addDataChildren = (commodityType: CommodityType) => {
    currentAddChildCommodityType.value = {
      id: commodityType.id,
      name: commodityType.name,
      status: commodityType.status,
      level: commodityType.level as 1 | 2,
      parentId: commodityType.parentId,
    }
    addChildCommodityTypeDialogVisible.value = true
  }

  //列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }
  const loading = ref(false)
  const tableData = ref<Array<CommodityType>>([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom
  const total = ref(0) // 总数目
  const addDialog = ref(false)
  const dialogTitle = ref('')
  const dialogLoading = ref(false)

  const formRef = ref<FormInstance>() // 表单元素
  // 表单数据
  const form = reactive({
    id: null,
    name: '',
    parentId: '',
    status: false,
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  })

  // 获取列表选中的数据
  const selecttion = ref<Array<string>>([])
  const handleChange = (val) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    const res = await typeList()
    tableData.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
    loading.value = false
  }
  const objItem = ref({ level: 0, parentName: '' })

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data).then((res) => {
      dialogLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success == true) {
        addDialog.value = false
        getList()
      }
    })
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveDataMethod(typeSave, form)
      }
    })
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的类型`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的类型?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (res.data.success) {
            selecttion.value = []
            tableDom.value.clearSelection()
            getList()
          }
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (res.data.success) {
            selecttion.value = []
            tableDom.value.clearSelection()
            getList()
            if (dialog != '') {
              addDialog.value = false
            }
          }
        })
      }
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', typeDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', typeDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', typeDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', typeDelete, [form.id], 3, addDialog)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  .types {
    display: flex;
    flex-direction: column;
    height: 100%;
    row-gap: 5px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .btn_group {
        display: flex;
        gap: 5px;
      }

      .search {
        display: flex;
        gap: 5px;
      }
    }

    .table {
      max-height: calc(100% - 66px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }

  .form_content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
</style>
